<template>
  <!-- <Tabs type="editable-card" @edit="onEdit">
    <TabPane v-for="(item, index) in paneList" :key="item.id">
      <template #tab>
        <span>
          <DesktopOutlined />
          <span>({{ index + 1 }})</span>
          <span>{{ item.tab }}</span>
        </span>
      </template>
    </TabPane>
  </Tabs> -->
  <div ref="terminalRef" class="terminal-container"></div>
</template>

<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { DesktopOutlined } from '@ant-design/icons-vue';
import { useSocket } from '@boeyo/hooks';
import { FitAddon } from '@xterm/addon-fit';
import { WebLinksAddon } from '@xterm/addon-web-links';
import { TabPane, Tabs } from 'ant-design-vue';
import { Terminal } from 'xterm';

const socketUrl = ref('ws://124.222.224.186:8800');
const { message, messages, connect, disconnect, isConnected, sendMessage } =
  useSocket(computed(() => socketUrl.value));
watch(
  () => message.value,
  (val) => {
    console.log('服务端推送消息', val);
  },
);

const props = defineProps({});
const paneList = ref([
  {
    id: 1,
    tab: '中间件',
  },
  {
    id: 2,
    tab: '数据库',
  },
]);
const terminalRef = ref(null);
let command = '';
const term = new Terminal({
  cursorBlink: true,
  fontSize: 14,
  fontFamily: 'Consolas, "Courier New", monospace',
  theme: {
    background: '#000',
    foreground: '#ffffff',
  },
});
const fitAddon = new FitAddon();

onMounted(() => {
  term.loadAddon(fitAddon);
  term.loadAddon(new WebLinksAddon());

  if (terminalRef.value) {
    term.open(terminalRef.value);
    fitAddon.fit();
    const list = [
      'Welcome to Alpine!',
      '',
      'The Alpine Wiki contains a large amount of how-to guides and general',
      'information about administrating Alpine systems.',
      'See <http://wiki.alpinelinux.org/>.',
      '',
      'You can setup the system with the command:setup-alpine',
      '',
      'You may change this message by editing /etc/motd.`',
      '',
    ];

    term.write(list.join('\n\r'));
    term.write('e04964a8d7a1:~# ');

    // 处理用户输入
    term.onData((data) => {
      handleInput(data);
    });
  }

  // 窗口大小变化时调整终端大小
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  term.dispose();
  window.removeEventListener('resize', handleResize);
});

const handleResize = () => {
  fitAddon.fit();
};

const handleInput = (data) => {
  if (data === '\r') {
    // 回车
    executeCommand(command);
    command = '';
    term.write('\r\n1a8e3H8d3135:~# ');
  } else if (data === '\u007f') {
    // 退格
    if (command.length > 0) {
      command = command.substring(0, command.length - 1);
      term.write('\b \b');
    }
  } else if (data === '\x03') {
    console.log('按下了撤回建');
    term.write('^C \r\n1a8e3H8d3135:~# ');
  } else {
    const str = data.replace(/[\u4e00-\u9fa5]/g, '');

    command += str;
    term.write(str);
  }
};

const executeCommand = (cmd) => {
  console.log(cmd, 'cmd');

  // cmd = cmd.trim();

  // switch (cmd) {
  //   case 'help':
  //     term.writeln('\n\r help');
  //     break;
  //   case 'clear':
  //     term.clear();
  //     break;
  //   case 'about':
  //     term.writeln('\n\r test');
  //     break;
  //   case '':
  //     break;
  //   case cmd.startsWith('echo ') ? cmd : '':
  //     term.writeln(cmd.substring(5));
  //     break;
  //   default:
  //     term.writeln(`\n\rCommand not found: ${cmd}`);
  // }
};

const onEdit = (targetKey, action) => {
  console.log(targetKey, 'targetKey');
  console.log(action, 'action');
};
</script>

<style scoped lang="scss">
.terminal-container {
  width: 100%;
  height: 100%;
  padding: 10px;
  box-sizing: border-box;
  background: #000;
}

.xterm {
  padding: 10px;
}
:deep(.xterm-screen) {
  .xterm-helpers {
    opacity: 0;
    height: 0;
  }
}
:deep(.ant-tabs-nav) {
  background: #2c2e31;
  margin-bottom: 0;
  height: 45px;
  &::before {
    display: none;
  }
  .ant-tabs-tab {
    &::after {
      content: '';
      display: block;
      position: absolute;
      right: 0;
      top: 0;
      width: 80px;
      height: 100%;
      background: linear-gradient(90deg, transparent, #000);
      opacity: 0;
    }
  }
  .ant-tabs-tab,
  .ant-tabs-nav-add {
    border: none;
    &.ant-tabs-tab-active {
      .ant-tabs-tab-btn {
        color: #fff;
      }
      background: rgba(120, 94, 7);
    }
    &:hover {
      .ant-tabs-tab-remove {
        opacity: 1;
      }
      &::after {
        opacity: 1;
      }
    }
    .ant-tabs-tab-remove {
      position: absolute;
      z-index: 99;
      right: 20px;
      opacity: 0;
    }
  }
}
</style>
